// interrogation/history/history.js
const call = require('../../utils/request.js');
const util = require('../../utils/util.js');
const app = getApp();
let doctorId = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    havaYY: '',  //是否有预约
    doctorArr: [], //医生列表
    havaYY:false, //是否有预约
    btnText:{
      'yyz':{text:'问诊',class:''},
      'wz':{text:'问诊',class:'themebg'},
      'yy':{text:'预约',class:'yellobg'},
      'no':{text:'不可预约',class:''}
    },
    talkState:false, //是否显示弹窗
  },

  onLoad: function (options) {
    this.getDocList();
  },

  onReady: function () {

  },

  onShow: function () {

  },

  onHide: function () {
    this.hideWin();
  },

  //获取所有医师
  getDocList() {
    wx.showLoading({
      title: '正在加载',
      mask:true
    })
    call.post('/api/camera/history_doctors_list').then( (res)=> {
      wx.hideLoading();
      console.log("获取历史咨询医师列表", res);
      if (res.data.code == 0) {
        let arr = [];
        let havaYY = false;
        try{
          for(let i of res.data.data.list){
            if(i.list_status == 1) havaYY = true;
            arr.push({
              id: i.id,
              name: i.name,
              position: i.department_id + i.position,
              tag: i.tag.split(','),
              goodAt: i.good_at,
              is_consulting: i.is_consulting,
              photo: i.photo||'../../images/defDoctor.png',
              appointment:i.appointment,
              yytime:i.appointment?i.appointment.start_time.toString().substring(5,16):'',
              list_status:i.list_status==1?true:false,
              status:(i.list_status==1? //我预约的
                        ((util.judgeDate(new Date(),i.appointment.start_time) && util.judgeDate(i.appointment.end_time,new Date()))?'wz':'yyz') //判断是否出于预约时间
                        :(i.list_status==5?'no' //离线未开启预约的
                          :(i.is_booking==1? //我未预约 -》 已开启预约
                            (i.is_online==1?  //在线
                              (i.is_consulting==1?'yywz':'yy') //是否开启咨询
                              :'yy') //不在线，开启预约
                            :((i.is_online==1 && i.is_consulting==1)?'wz':'no') //未开启预约 -》 判断是否在线且开启咨询
                          )
                        )
                      ),
            });
          }
          this.setData({
            havaYY:havaYY,
            doctorArr:arr
          })
        }catch(err){}
      }
    });
  },

  // 显示弹窗
  showWin() {
    this.setData({
      talkState:true
    })
    app.globalData.doctorId = this.doctorId;
  },

  // 关闭弹窗
  hideWin() {
    this.setData({
      talkState:false
    })
  },

  //预约问诊按钮操作
  toWz(e){
    const status = e.currentTarget.dataset.status;
    const id =  e.currentTarget.dataset.idx;
    if(status == 'yy'){ //预约操作
      if(!this.data.havaYY){
        wx.navigateTo({
          url: `../subscribe/subscribe?id=${id}`
        });
      }
    }else if(status == 'wz'){ //问诊操作
      this.doctorId = id;
      this.showWin();
    }
  },

  //跳转到图文问诊
  toUrl() {
    this.hideWin();
    wx.navigateTo({
      url: "../chat/chat?id=".concat(this.doctorId) 
    });
  },

  //跳转到医生页面
  toDoctor(e){
    const index = e.currentTarget.dataset.index;
    wx.setStorageSync('doctor', JSON.stringify({
      obj:this.data.doctorArr[index],
      havaYY:this.data.havaYY
    }))
    wx.navigateTo({
      url: "../doctor/doctor"
    });
  },

  //视频问诊
  video() {
    this.hideWin();
    wx.showLoading({
      title: '正在获取数据',
      mask:true
    })
    call.post('/api/camera/get_available_order',{doctor_id:this.doctorId}).then( (res)=> {
      wx.hideLoading();
      console.log("是否已有支付", res.data);
      if (res.data.data && (res.data.data.not_used_order || res.data.data.appointment_data)) {//已支付
        wx.showLoading({
          title: '正在获取数据',
          mask:true
        })
        let trade_no = null; 
        let duration = 0;
        let isyy = 1;
        if(res.data.data.appointment_data){ //查看是否有预约
          trade_no = res.data.data.appointment_data.trade_no; 
          isyy = 2;
          let endtime = res.data.data.appointment_data.start_time.toString().replace(/-/g,"/");
              endtime = new Date(endtime);
              endtime = endtime.getTime();
              
          let nowtime = new Date();
              nowtime = nowtime.getTime();
          duration = (parseFloat(nowtime)-parseFloat(endtime))/1000;
          console.log("已浪费多少秒呢",duration)
        }else if(res.data.data.not_used_order){ //正常视频问诊
          trade_no = res.data.data.not_used_order.trade_no; 
          duration = res.data.data.not_used_order.duration;
        }
        wx.setStorageSync('sp_duration', duration); //已用时长
        call.post('/api/camera/gen_trtc_sign',{user_id:app.globalData.sid}).then( (res1)=> {
          wx.hideLoading();
          console.log('获取签名',res1)
          if(res1.data.code == 0){
            const d = res1.data.data;
            wx.navigateTo({url:`../video/video?sdkAppid=${d.sdkAppid}&userSign=${d.userSgin}&tradeNo=${trade_no}&isyy=${isyy}`})
          }else{
            wx.showToast({
              title: '获取视频签名失败',
              icon:'none'
            })
          }
        })
        
      }else if(res.data.msg){
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
        this.hideWin();
      } else {//未支付
        wx.navigateTo({
          url: '../buy/buy?type=1' 
        });
      }
    });
  },
})